package com.jiexin.service;

import com.google.common.base.Joiner;
import com.jiexin.beans.CacheKeyConstants;
import com.jiexin.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

import javax.annotation.Resource;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 19:56 2018/4/30 0030
 * @Modified By:
 */
@Service
@Slf4j
public class SysCacheService {

    //原RedisPool是放在common包下的，并没有被Sping容器管理。
    //方案1.将RedisPool放入spring容器自动扫描的包下
    //方案2.给common包添加自动扫描
    @Resource(name = "redisPool")
    private RedisPool redisPool;

    //保存缓存
    //待保存的是固定缓存key值
    public void saveCache (String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
        saveCache(toSavedValue, timeoutSeconds, prefix, null);
    }

    //待保存的是通过keys动态拼接缓存key值
    public void saveCache (String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
        if (toSavedValue == null) {
            return;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = redisPool.instance();
            String cacheKey = generateCacheKey(prefix, keys);
            shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);
        } catch (Exception e) {
            log.error("save cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
        } finally {
            redisPool.safeClose(shardedJedis);
        }
    }

    public String getFromCache (CacheKeyConstants prefix, String... keys) {
        String cacheKey = generateCacheKey(prefix, keys);
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis =redisPool.instance();
            String value = shardedJedis.get(cacheKey);
            return value;
        } catch (Exception e) {
            log.error("get cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
            return null;
        } finally {
            redisPool.safeClose(shardedJedis);
        }
    }

    public String generateCacheKey(CacheKeyConstants prefix, String... keys) {
        //获取缓存的常量key值
        String key = prefix.name();
        //若是keys有值，则代表需要动态拼接，则去与常量拼接key值
        if (keys != null && keys.length > 0) {
            key += "_" + Joiner.on("_").join(keys);
        }
        return key;
    }
}
